package com.yayohos.locationmanager.view;


import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.app.Context;

import java.lang.ref.WeakReference;

/**
 * ContextProcessor
 *
 * @date 2021/5/26
 */
public class ContextProcessor {
    private Context applicationContext;
    private WeakReference<Ability> weakAbility;
    private WeakReference<AbilitySlice> weakSlice;

    public ContextProcessor(Context context) {
        applicationContext = context;
        weakAbility = new WeakReference<>(null);
        weakSlice = new WeakReference<>(null);
    }

    /**
     * if use in AbilitySlice,return this AbilitySlice
     *
     * @return AbilitySlice
     */
    public AbilitySlice getAbilitySlice() {
            return weakSlice.get();
    }

    /**
     * setAbilitySlice
     *
     * @param abilitySlice In order to use in AbilitySlice
     * @return ContextProcessor
     */
    public ContextProcessor setAbilitySlice(AbilitySlice abilitySlice) {
        weakAbility = new WeakReference<>(null);
        weakSlice = new WeakReference<>(abilitySlice);
        return this;
    }

    /**
     * if use in Ability or Service,return this Ability or Service
     *
     * @return Ability
     */
    public Ability getAbility() {
        if (weakAbility.get() != null) {
            return weakAbility.get();
        }
        if (getAbilitySlice() != null) {
            return getAbilitySlice().getAbility();
        }
        return null;
    }

    /**
     * setAbility
     *
     * @param ability In order to use in Ability or Service
     * @return ContextProcessor
     */
    public ContextProcessor setAbility(Ability ability) {
        weakAbility = new WeakReference<>(ability);
        weakSlice = new WeakReference<>(null);
        return this;
    }

    /**
     * get the applicationContext
     *
     * @return Context
     */
    public Context getContext() {
        return applicationContext;
    }
}
